package cn.yuysaln.domain.strategy.service.rule.tree.impl;

import cn.yuysaln.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.yuysaln.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cn.yuysaln.domain.strategy.repository.IStrategyRepository;
import cn.yuysaln.domain.strategy.service.armory.IStrategyDispatch;
import cn.yuysaln.domain.strategy.service.rule.tree.ILogicTree;
import cn.yuysaln.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTree {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减-开始 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        //先从redis扣减
        Boolean isSubtracted = strategyDispatch.subtractionAwardStock(strategyId, awardId,endDateTime);

        if (isSubtracted){
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            //扣减库存的对象是redis，涉及到mysql的一致性问题
            //为了减小MySQL的连接压力，把减库存的操作加入到redis中的 “写延迟” 队列
            strategyRepository.awardStockConsumeSendQueue(
                    StrategyAwardStockKeyVO.builder()
                            .strategyId(strategyId)
                            .awardId(awardId)
                            .build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();


        }

        // 如果库存不足，则直接返回放行
        log.warn("规则过滤-库存扣减-告警，库存不足。userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.ALLOW)
                .build();

    }
}
